import { PageContainer } from '@ant-design/pro-layout';
import { Button,message} from 'antd';
import ProTable from '@ant-design/pro-table';
import type { ProColumns} from '@ant-design/pro-table';
import React from 'react';
import {RebateItem,NormalListParam,Dealer} from '../../model'
import { FileExcelOutlined, PlusOutlined} from '@ant-design/icons';
import ProForm,{ DrawerForm,ProFormText,ProFormTextArea,ProFormDigit, ModalForm, ProFormUploadDragger } from '@ant-design/pro-form';
import request from '@/utils/request';
import DealerDialog from '../../components/Common/DealerDialog'
import { Spin } from 'antd';
import { Modal } from 'antd';
import { Table } from 'antd';
import {exportFile} from '@/utils/utils';
const JXS_FLAG = sessionStorage.getItem('access') as string ==='jxs-1'

class DealerManager extends React.Component {
  actionRef = React.createRef<any>();

  async allRebateData(params: NormalListParam) {
    var data =  request('/xwyl/rebate/allRebateData', {
      params,
    });
    return data;
  }
  
  async exportRebate(params: any){
    var data =  request('/xwyl/rebate/exportRebate', {
      params,
      method: 'POST',
    });
    return data;
  }

  saveRebate(params:any){
    return request('/xwyl/rebate/saveRebate', {
      method: 'POST',
      requestType:'form',
      data: {
        ...params,
        method: 'post',
      },
    });
  }

  state = {
    showCreate:false, 
    dealDialog:false,
    dealer:undefined,
    spinningFlag:false,
    showImport:false,
    errInfo:[],
    errorVisible:false,
  };

  access = sessionStorage.getItem('access') as string;

  dealer:Dealer | undefined;
  formRef = React.createRef<any>();

  setShowCreate=(flag:boolean)=>{
    this.setState({showCreate:flag});
  }
  
   columns: ProColumns<RebateItem>[] = [
    {
      title:"客户代码",
      dataIndex: 'dealerCode',
      hideInSearch:JXS_FLAG,
      width:100,
      hideInTable:JXS_FLAG
    },
    {
      title:"客户名称",
      dataIndex: 'dealerName',
      hideInSearch:JXS_FLAG,
      ellipsis:true,
      width:200,
      hideInTable:JXS_FLAG
    },
    {
      title:'日期',
      dataIndex: 'rebate_time',
      valueType:'date',
      hideInSearch:true,
    },
    {
      title:"收入/支出",
      dataIndex: 'text',
      width:120,
      valueType:'select',
      valueEnum: {
        add: { text: '收入' },
        delete: { text: '支出' },
      },
      renderText: (val,record: RebateItem) =>
      {
        return (record.action==="add"?"收入":"支出")
      }
    },
    {
      title:'订单号',
      dataIndex: 'orderNumber',
      hideInSearch:true,
    },
    {
      title:"金额",
      dataIndex: 'amount',
      valueType:'money',
      hideInSearch:true,
    },
    {
      title:"备注",
      dataIndex: 'note',
      hideInSearch:true,
    },
    {
      title:'选择日期',
      valueType:'dateRange',
      dataIndex: 'date',
      hideInTable:true,
    },
    
  ];

  componentDidMount() {
  }

  onFileUpload=(info:any)=>{
    if (info.file.status !== 'uploading') {
    }
    if (info.file.status === 'done') {
      if(info.file.response.errorCode==='200'){
        message.success(`${info.file.name} 上传成功，后台正在处理...`);
        this.actionRef.current?.reloadAndRest?.();
        this.setState({showImport:false});
      }else{
       message.error('上传失败: '+info.file.response.msg);
        this.setState({errorVisible:true,errInfo:info.file.response.data});
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败！`);
    }
  }

  errorColumn=[
    {
      title: '错误行',
      dataIndex: 'rownum',
    },
    {
      title: '错误信息',
      dataIndex: 'errerMsg',
    },
  ]
  
  handleCancel=()=>{
    this.setState({errorVisible:false,errInfo:[]});
  }

  render(){

    const {showCreate} = this.state;
    return (
      <PageContainer>
      <ProTable<RebateItem>
          scroll={{x:1300}}
          search={{
            span: 6,
            defaultCollapsed: false,
            collapseRender:false,
          optionRender: ({ searchText, resetText }, { form }) => [
            <Button
              key="search"
              type="primary"
              onClick={() => {
                form?.submit();
              }}
            >
              {searchText}
            </Button>,
            <Button
              key="rest"
              onClick={() => {
                form?.resetFields();
                form?.submit();
              }}
            >
              {resetText}
            </Button>,
            <Button key="out" hidden={JXS_FLAG} onClick={async()=>{
              this.setState({spinningFlag:true});
              var date = form?.getFieldValue("date");
              var params:any={};
              if(date){
                params.beginDate=date[0].format('YYYY-MM-DD');
                params.endDate=date[1].format('YYYY-MM-DD');
                params.date=undefined;
              }
              params.text = form?.getFieldValue("text");
              params.dealerCode = form?.getFieldValue("dealerCode");
              params.dealerName = form?.getFieldValue("dealerName");
              var val = await this.exportRebate(params);
              if(val.errorCode==='200'){
                exportFile(val.data,'返利.xlsx')
              }else{
                message.error(val.errorMessage);
              }
              this.setState({spinningFlag:false});
            }}>导出</Button>,
          ],
          }}
          request={async(params, sorter, filter) => {
            if(params.date){
              params.beginDate=params.date[0];
              params.endDate=params.date[1];
              params.date=undefined;
            }
            return this.allRebateData({ ...params, sorter, filter })
          }}
          columns={this.columns}
          actionRef={this.actionRef}
          rowKey="id"
          pagination={{
            pageSizeOptions:['20', '100', '500']
          }}
          toolBarRender={() => JXS_FLAG?[]:[
            <Button
              type="primary"
              key="primary"
              hidden={this.access==='analysis'}
              onClick={() => {
                this.setShowCreate(true);
              }}
            >
              <PlusOutlined />新建
            </Button>,
            <Button
            type="primary"
            key="primary"
            hidden={this.access==='analysis'}
            onClick={async() => {
              this.setState({showImport:true});
            }}
          >
          <FileExcelOutlined />导入
          </Button>
          ]}
          toolbar={{settings:[]}}
          />
          <DrawerForm
            title="新增返利"
            formRef={this.formRef}
            onVisibleChange={this.setShowCreate}
            visible={showCreate}
            onFinish={async (values: any) => {
                values.dealerId = this.dealer?.id;
                var result = await this.saveRebate(values);
                if(result.errorCode==='200'){
                  this.actionRef?.current?.reloadAndRest?.();
                  return true;
                }else{
                  message.error("添加失败");
                  return false;
                }
            }}
         >
            <ProForm.Group>
              <ProFormText width='xl' name="cnName" label="客户" disabled placeholder="请选择客户" rules={[
                  {
                    required: true,
                  },
                ]} 
                />
                <Button type="primary" key="primary" style={{marginTop:'4px'}} onClick={() => {
                    this.setState({dealDialog:true});
                }}>选择客户</Button>
            </ProForm.Group>
           <ProFormDigit  width='xl' name="amount" label="返利余额" placeholder="请输入返利余额"
              rules={[
                {
                  required: true,
                },
              ]} />
            <ProFormTextArea name="note" label="备注" placeholder="请输入备注" fieldProps={{showCount:true,maxLength:200}} />
        </DrawerForm>
        <DealerDialog
            mode="single"
            onCancel={() => {
              this.setState({dealDialog:false});
            }}
            onSubmit={async (value) => {
              this.dealer = value[0];
              this.formRef.current.setFieldsValue({"cnName":value[0].cnName});
              this.setState({dealDialog:false});
            }}
            modalVisible={this.state.dealDialog}
            values={[]}
           >
        </DealerDialog>

        <ModalForm
            title="初始库存上报"
            onVisibleChange={v=>{
              this.setState({showImport:v});
            }}
            modalProps={{
              destroyOnClose:true,
              forceRender:true
            }}
            visible={this.state.showImport}
            onFinish={async (values: any) => {
              console.log(values);
               return true;
            }}
         >
             <div style={{margin:'10px 0 20px 0'}}><a href="/xwyl/attach/fl.xlsx" download="返利模板.xlsx"><Button type="primary"> <FileExcelOutlined />返利模板下载</Button></a></div>
            <ProFormUploadDragger label="选择excel上传" name="file" action='/xwyl/rebate/rebateImport' fieldProps={{name:'file',headers:{'authorization':sessionStorage.getItem('token') as string}}}  max={1} onChange={this.onFileUpload} />

         </ModalForm>
         <Modal
          visible={this.state.errorVisible}
          title="导入错误提示"
          width={800}
          footer={null}
          destroyOnClose={true}
          onCancel={this.handleCancel}
        >
        <Table dataSource={this.state.errInfo} style={{height:400}} columns={this.errorColumn} pagination={false} rowKey="rownum"
></Table>
      </Modal>
        <Spin spinning={this.state.spinningFlag} style={{transform:'translate(-50%,-50%)',left:'50%',top:'50%',position:'absolute'}}/>
       </PageContainer>
    )
  }
}


export default DealerManager
